<!-- 该画面是维护项目维护画面中的一个子画面，用于创建或更新维护项目信息。 -->
<template>
  <el-dialog
    :visible.sync="openSheet"
    width="1200px"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :before-close="cancel"
    append-to-body
  >
    <!-- 项目报价单信息：开始 -->
    <projectquota-info :project-quota-information="projectQuotaInformation" />
    <!-- 项目报价单信息：结束 -->
    <br>
    <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('quoteNo')" prop="quoteFK" :error="error.quoteFK">
            <el-select v-model="form.quoteFK" clearable filterable :placeholder="$t('inputquoteNo')" style="width: 100%" @change="handleChange">
              <el-option v-for="item in quoteOption" :key="item.quote_no" :label="item.quote_content" :value="item.id">
                <span style="float: left">{{ item.quote_no }}</span>
                <span style="float: right; font-size: 13px;color: var(--el-text-color-secondary);">{{ item.quote_content }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('projectDevelopName')" prop="project_name" :error="error.project_name">
            <el-input v-model="form.project_name" maxlength="50" show-word-limit :placeholder="$t('inputprojectDevelopName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopOrderNo')" prop="order_no" :error="error.order_no">
            <el-input v-model="form.order_no" maxlength="10" show-word-limit :placeholder="$t('inputprojectDevelopOrderNo')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopSalesDate')" prop="sales_date" :error="error.sales_date">
            <el-date-picker v-model="form.sales_date" type="date" value-format="yyyy-MM-dd" :placeholder="$t('inputprojectDevelopSalesDate')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopQuoteAmount')" prop="quote_amount" :error="error.quote_amount">
            <el-input v-model="form.quote_amount" :placeholder="$t('inputprojectDevelopQuoteAmount')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopQuoteDays')" prop="quoted_days" :error="error.quoted_days">
            <el-popover content="报价单中的报价工数" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.quoted_days" :placeholder="$t('inputprojectDevelopQuoteDays')" @change="handleQuoteDaysChange" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopSalesAmount')" prop="sales_amount" :error="error.sales_amount">
            <el-popover content="(A1+A2+A3)*300" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.sales_amount" :placeholder="$t('inputprojectDevelopSalesAmount')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopProfit')" prop="operating_profit" :error="error.operating_profit">
            <el-popover content="报价金额 - 预定销售金额" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.operating_profit" :placeholder="$t('inputprojectDevelopProfit')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopMargin')" prop="operating_margin" :error="error.operating_margin">
            <el-popover content="营业利润/报价金额" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.operating_margin" :placeholder="$t('inputprojectDevelopMargin')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopReserveAmount')" prop="reserve_amount" :error="error.reserve_amount">
            <el-input v-model="form.reserve_amount" :placeholder="$t('inputprojectDevelopReserveAmount')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopQuoteHours')" prop="quoted_hours" :error="error.quoted_hours">
            <el-popover content="报价工数*7" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.quoted_hours" :placeholder="$t('inputprojectDevelopQuoteHours')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopA1BudgetHours')" prop="a1bugdget_hours" :error="error.a1bugdget_hours">
            <el-popover content="报价工时*0.75" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.a1bugdget_hours" :placeholder="$t('inputprojectDevelopA1BudgetHours')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopA2BudgetHours')" prop="a2manage_hours" :error="error.a2manage_hours">
            <el-popover content="报价工时*0.05" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.a2manage_hours" :placeholder="$t('inputprojectDevelopA2BudgetHours')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('projectDevelopA3BudgetHours')" prop="a3risk_hours" :error="error.a3risk_hours">
            <el-popover content="A1+A2+A3<=报价工时*0.8" placement="bottom-start" effect="light">
              <template #reference>
                <el-input v-model="form.a3risk_hours" :placeholder="$t('inputprojectDevelopA3BudgetHours')" />
              </template>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('projectDevelopNote')" prop="note" :error="error.note">
            <el-input v-model="form.note" maxlength="150" show-word-limit :placeholder="$t('inputprojectDevelopNote')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="createFlag" type="primary" @click="submitForm">{{
        $t('create')
      }}</el-button>
      <el-button v-else type="primary" @click="submitForm">{{
        $t('update')
      }}</el-button>
      <el-button @click="cancel">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createProjectDevelopApi, updateProjectDevelopApi, getProjectDevelopInitDataApi } from '../api/projectdevelop.api';
import { getProjectQutaListApi } from '@/views/project/projectquota/api/projectquota.api'
import projectquotaInfo from '@/views/project/projectquota/components/projectquota-info.vue';

export default {
  components: { projectquotaInfo },
  data() {
    return {
      formRef: 'form',
      openSheet: false,
      createFlag: true,
      createTitle: this.$t('projectDevelopCreateTitle'),
      updateTitle: this.$t('projectDevelopUpdateTitle'),
      quoteOption: [],
      AllquoteOption: [],
      projectPlanId: 0,
      projectQuotaInformation: {},
      form: {
        projectPlanFK: undefined,
        quoteFK: undefined,
        project_name: undefined,
        order_no: undefined,
        sales_date: undefined,
        quote_amount: undefined,
        sales_amount: undefined,
        operating_profit: undefined,
        operating_margin: undefined,
        reserve_amount: undefined,
        quoted_days: undefined,
        quoted_hours: undefined,
        a1bugdget_hours: undefined,
        a2manage_hours: undefined,
        a3risk_hours: undefined,
        note: undefined
      },
      error: {
        projectPlanFK: undefined,
        quoteFK: undefined,
        project_name: undefined,
        order_no: undefined,
        sales_date: undefined,
        quote_amount: undefined,
        sales_amount: undefined,
        operating_profit: undefined,
        operating_margin: undefined,
        reserve_amount: undefined,
        quoted_days: undefined,
        quoted_hours: undefined,
        a1bugdget_hours: undefined,
        a2manage_hours: undefined,
        a3risk_hours: undefined,
        note: undefined
      },
      rules: {
        quoteFK: [{ required: true, message: this.$t('projectDevelopQuoteisRequired'), trigger: 'blur' }],
        project_name: [{ required: true, message: this.$t('projectDevelopNameisRequired'), trigger: 'blur' }],
        order_no: [{ required: true, message: this.$t('projectDeveloporderNoisRequired'), trigger: 'blur' }],
        quote_amount: [{ required: true, message: this.$t('projectDevelopQuoteAmountisRequired'), trigger: 'blur' }],
        sales_amount: [{ required: true, message: this.$t('projectDevelopSalesAmountisRequired'), trigger: 'blur' }],
        operating_profit: [{ required: true, message: this.$t('projectDevelopProfitisRequired'), trigger: 'blur' }],
        operating_margin: [{ required: true, message: this.$t('projectDevelopMarginisRequired'), trigger: 'blur' }],
        quoted_days: [{ required: true, message: this.$t('projectDevelopQuoteDaysisRequired'), trigger: 'blur' }],
        quoted_hours: [{ required: true, message: this.$t('projectDevelopQuoteHoursisRequired'), trigger: 'blur' }],
        a1bugdget_hours: [{ required: true, message: this.$t('projectDevelopA1BudgetHoursisRequired'), trigger: 'blur' }]
      }
    };
  },
  computed: {
    labelWidth() {
      return this.$i18n.locale === 'en' ? '150px' : '110px';
    }
  },
  methods: {
    openSheetDialog(data, developdata) {
      this.openSheet = !this.openSheet;
      this.reset();
      this.initialize();
      if (developdata) {
        this.title = this.updateTitle;
        this.createFlag = false
        this.form = { ...developdata };
        this.developid = developdata.id;
        this.getQuoteById(this.form.quoteFK)
      } else {
        this.title = this.createTitle;
        this.createFlag = true;
        this.developid = undefined
      }
      this.projectPlanId = data.id;
    },
    reset() {
      this.resetForm('form');
      this.resetJsonObject(this.form);
      this.projectQuotaInformation = {}
    },
    cancel() {
      this.openSheet = !this.openSheet;
    },
    initialize() {
      this.getQuoteData()
    },
    // 获取报价单List
    async getQuoteData(query) {
      //   表示开发项目
      query = 'D'
      var resp = await getProjectQutaListApi({ quote_type: query, page: 1, page_size: 20 })
      if (resp.success) {
        this.AllquoteOption = resp.data.results;
      } else {
        this.AllquoteOption = [];
      }
      this.quoteOption = this.AllquoteOption.filter(item => item.projectPlanFK === this.projectPlanId);
    },
    // 通过报价单ID获取对应数据
    async getQuoteById(query) {
      var resp = await getProjectQutaListApi({ id: query, page: 1, page_size: 20 })
      if (resp.success) {
        const list = resp.data.results;
        this.projectQuotaInformation = { ...list[0] }
      } else {
        this.projectQuotaInformation = {};
      }
    },
    // 获取初始值
    async handleChange() {
      if (this.form.quoteFK) {
        const data = this.quoteOption.filter(item => item.id === this.form.quoteFK);
        this.projectQuotaInformation = { ...data[0] }
        this.form.projectPlanFK = this.projectPlanId
        var resp = await getProjectDevelopInitDataApi(this.form)
        if (resp.success) {
          this.form.sales_date = resp.data.sales_date
          this.form.quote_amount = resp.data.quote_amount
          this.form.sales_amount = resp.data.sales_amount
          this.form.operating_profit = resp.data.operating_profit
          this.form.operating_margin = resp.data.operating_margin
          this.form.quoted_days = resp.data.quoted_days
          this.form.quoted_hours = resp.data.quoted_hours
          this.form.a1bugdget_hours = resp.data.a1bugdget_hours
          this.form.a2manage_hours = resp.data.a2manage_hours
          this.form.reserve_amount = resp.data.reserve_amount
          this.form.a3risk_hours = resp.data.a3risk_hours
        } else {
          this.reset()
        }
      } else {
        this.reset()
      }
    },
    // 报价天数发生改变时触发，计算报价工时、A1、A2、预定销售金额
    handleQuoteDaysChange() {
      if (this.form.quoted_days) {
        this.form.quoted_hours = parseFloat((this.form.quoted_days * 7).toFixed(2));
        this.form.a1bugdget_hours = parseFloat((this.form.quoted_hours * 0.75).toFixed(2));
        this.form.a2manage_hours = parseFloat((this.form.quoted_hours * 0.05).toFixed(2));
        this.form.a3risk_hours = 0;
        this.form.sales_amount = parseFloat(((this.form.a1bugdget_hours + this.form.a2manage_hours + this.form.a3risk_hours) * 300).toFixed(2));
        if (this.form.quote_amount) {
          this.form.operating_profit = parseFloat((this.form.quote_amount - this.form.sales_amount).toFixed(2));
          this.form.operating_margin = parseFloat(((this.form.operating_profit / this.form.quote_amount) * 100).toFixed(2));
          this.form.reserve_amount = 0;
        }
      }
    },
    // 报价金额发生改变时触发，计算利润、利润率
    handleQuoteAmountChange() {
      if (this.form.quote_amount && this.form.quoted_days) {
        this.form.operating_profit = parseFloat((this.form.quote_amount - this.form.sales_amount).toFixed(2));
        this.form.operating_margin = parseFloat(((this.form.operating_profit / this.form.quote_amount) * 100).toFixed(2));
        this.form.reserve_amount = 0;
      }
    },
    submitForm: function() {
      this.$refs['form'].validate(async(Valid) => {
        if (Valid) {
          this.resetJsonObject(this.error);
          var Resp;
          if (this.createFlag) {
            Resp = await createProjectDevelopApi(this.form);
          } else {
            Resp = await updateProjectDevelopApi(this.developid, this.form);
          }
          if (Resp.success) {
            this.$emit('refreshList');
            this.cancel();
            if (this.createFlag) {
              this.targaMessage(
                this.$t('createSuccess', {
                  title: this.$t('projectDevelopOrderNo'),
                  value: this.form.order_no
                })
              );
            } else {
              this.targaMessage(
                this.$t('updateSuccess', {
                  title: this.$t('projectDevelopOrderNo'),
                  value: this.form.order_no
                })
              );
            }
          } else {
            if (typeof Resp.msg === 'object') {
              this.error = Resp.msg;
            } else {
              this.targaMessageBox(this, Resp.msg);
            }
          }
        }
      });
    }
  }
};
</script>

  <style scoped>

  </style>
